package org.example.wx.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.common.constant.Issuer;
import org.example.common.utils.CommonUtil;
import org.example.common.utils.DateTimeUtil;
import org.example.common.utils.IpUtil;
import org.example.common.utils.ResponseUtil;
import org.example.db.entity.WxUser;
import org.example.db.mapper.WxUserMapper;
import org.example.security.util.JwtTokenUtil;
import org.example.wx.dto.UserInfo;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@Slf4j
public class WxAuthService {

    WxMaService wxMaService;
    WxUserMapper wxUserMapper;
    JwtTokenUtil jwtTokenUtil;

    public WxAuthService(WxMaService wxMaService, WxUserMapper wxUserMapper, JwtTokenUtil jwtTokenUtil) {
        this.wxMaService = wxMaService;
        this.wxUserMapper = wxUserMapper;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    /**
     * 通过微信登陆
     * @param code 微信小程序code
     * @param userInfo 用户信息
     * @param request /
     * @return token
     */
    public String login(String code, UserInfo userInfo, HttpServletRequest request){


        String sessionKey = null;
        String openid = null;
        try {
            WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();
            openid = result.getOpenid();
        } catch (Exception e) {
            log.error("wxMaService error");
            log.error(e.getMessage(), e);
            ResponseUtil.fail();
        }

        if (sessionKey == null || openid == null) {
            throw new RuntimeException();
        }

        List<WxUser> wxUsers = wxUserMapper.selectList(new QueryWrapper<WxUser>().lambda().eq(WxUser::getWeixinOpenid, openid));
        WxUser wxUser = null;
        if (wxUsers.size() == 0) {
            wxUser = new WxUser();
            wxUser.setWeixinOpenid(openid);
            wxUser.setAvatar(userInfo.getAvatar());
            wxUser.setNickname(userInfo.getNickName());
            wxUser.setGender(userInfo.getGender());
            wxUser.setLastLoginTime(DateTimeUtil.getDateTimeString());
            wxUser.setLastLoginIp(IpUtil.getIpAddr(request));
            wxUser.setSessionKey(sessionKey);

            wxUserMapper.insert(wxUser);

        } else {
            wxUser = wxUsers.get(0);
            wxUser.setLastLoginTime(DateTimeUtil.getDateTimeString());
            wxUser.setLastLoginIp(IpUtil.getIpAddr(request));
            wxUser.setSessionKey(sessionKey);
            int count = wxUserMapper.updateById(wxUser);
            CommonUtil.isSqlExcute(count);
        }

        // 生成token

        return jwtTokenUtil.generateToken(String.valueOf(wxUser.getId()), Issuer.fromWx);
    }
}
